<?php
// +----------------------------------------------------------------------
// | 有小象汇 自研正版源码 赋能开发者
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 http://www.uxphp.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 有小象汇并不是自由软件，未经许可不能去掉有小象汇相关版权
// +----------------------------------------------------------------------
// | Author:  有小象汇
// +----------------------------------------------------------------------

namespace app\api\controller\v1\car;


use app\model\car\CarOrder;
use app\model\car\CarOrderRerent;
use app\model\car\CarOrderTake;
use app\model\user\User;
use app\Request;
use app\services\car\CarOrderRerentServices;
use app\services\car\CarOrderServices;
use app\services\car\CarOrderTakeServices;
use app\services\car\OrderPayServices;
use think\exception\ValidateException;

class CarOrderController
{
    protected $services = NULL;

    /**
     * CarOrderController constructor.
     * @param CarOrderServices $services
     */
    public function __construct(CarOrderServices $services){
        $this->services = $services;
    }

    /**
     * 列表
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOrderList(Request $request){
        $where = $request->postMore([
            ['status',''],
        ]);
        $where['uid'] = $request->uid();
        return app('json')->success($this->services->getList($where,true));
    }

    /**
     * 订单详情
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOrderDetail(Request $request){
        $data = $request->getMore([
            ['order_id',''],
        ]);
        if(!$data['order_id']) return app('json')->fail('参数错误');
        return app('json')->success($this->services->getOrderInfo((int)$data['order_id']));
    }

    /**
     * 费用明细
     * @param Request $request
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOrderCost(Request $request){
        $data = $request->getMore([
            ['order_id',''],
        ]);
        if(!$data['order_id']) return app('json')->fail('参数错误');
        return app('json')->success($this->services->getOrderCost((int)$data['order_id']));
    }

    /**
     * 取消订单
     * @param Request $request
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function orderCancel(Request $request){
        $data = $request->postMore([
            ['order_id',''],
        ]);
        $user = $request->user()->toArray();
        $user['id'] = $user['uid'];
        $user['user_name'] = $user['nickname'];
        if(!$data['order_id']) return app('json')->fail('参数错误');
        return app('json')->success($this->services->orderCancel((int)$data['order_id'],$user,1));
    }

    /**
     * 获取续租订单
     * @param Request $request
     * @param CarOrderRerentServices $services
     * @return mixed
     */
    public function getRerentList(Request $request,CarOrderRerentServices $services){
        $data = $request->getMore([
            ['order_id',0],
            ['rerent_status','']
        ]);
        if(!$data['order_id']) return app('json')->fail('参数错误');
        return app('json')->success($services->getList($data,true));
    }

    /**
     * 续租订单详情
     * @param Request $request
     * @param CarOrderRerentServices $services
     * @return mixed
     */
    public function getRerentDetail(Request $request,CarOrderRerentServices $services){
        $data = $request->getMore([
            ['rerent_id',''],
        ]);
        if(!$data['rerent_id']) return app('json')->fail('参数错误');
        return app('json')->success($services->getRerentInfo((int)$data['rerent_id']));
    }

    /**
     * 续租订单支付
     * @param Request $request
     * @param CarOrderRerentServices $services
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function payRerent(Request $request,CarOrderRerentServices $services){
        $data = $request->postMore([
            ['rerent_id',0],
            ['pay_type','weixin'],
        ]);

        $rerent = CarOrderRerent::find($data['rerent_id']);
        $rerent = $rerent ? $rerent->toArray() : [];
        if(!$rerent) throw new ValidateException('未查询到订单信息');
        if($rerent['pay_time'] > 0) throw new ValidateException('订单已支付,不可重复支付');
        if(!$data['rerent_id']) return app('json')->fail('参数错误');
        $op_user = $request->user();
        $op_user['user_name'] = $op_user['nickname'];
        /** @var OrderPayServices $payServices */
        $payServices = app()->make(OrderPayServices::class);
        switch ($data['pay_type']){
            case 'yue':
                if($op_user['now_money'] < $rerent['rerent_price']) throw new ValidateException('余额不足，请及时充值');
                $pay = $payServices->yueOrderRerentPay($rerent,$op_user,1);
                if($pay['status'] === true){
                    return app('json')->status('success','余额支付成功',[]);
                }else{
                    throw new ValidateException('余额支付失败');
                }
                break;
            case 'Offline':
                break;
            case 'weixin':
                if($rerent['rerent_price'] <= 0){
                    throw new ValidateException('支付订单金额不能小于或等于0');
                }else{
                    $from = 'routine';
                    $jsConfig = $payServices->rerentPay($rerent,$from,$op_user,1);
                    return app('json')->status('wechat_pay', ['jsConfig' => $jsConfig, 'rerent_id' => $rerent['id']]);
                }
                break;
        }
    }

    /**
     * 获取续租退款订单
     * @param Request $request
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getRefundRerent(Request $request){
        $data = $request->getMore([
            ['rerent_id',0],
        ]);
        return app('json')->success($this->services->getRerentRefund((int)$data['rerent_id']));
    }

    /**
     * 创建订单
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function creatCarOrder(Request $request)
    {
        $data = $request->postMore([
            ['type_id', 0],       //车型信息
            ['contact_id', 0],    //预订人信息
            ['take_city_id',0],   //取车城市
            ['return_city_id',0], //还车城市
            ['store_id',0],       //门店
            ['take_place_id',0],  //取车服务点
            ['take_title',0],     //取车地点名称
            ['take_latitude',0],  //纬度
            ['take_longitude',0], //经度
            ['home_take_km',0],//
            ['home_take_price',0],//
            ['return_place_id',0],
            ['return_title',0],
            ['return_latitude',0],
            ['return_longitude',0],
            ['home_return_km',0],  //
            ['home_return_price',0],//
            ['start_time',0],
            ['end_time',0],
            ['car_price',0],
            ['car_fee',0],
            ['service_cost',0],
            ['car_service',[]],  //保险费用基础服务费，保险费
            ['fee',[]],           //费用合集
            ['coupon_user_id',0],
            ['coupon_price',0],
            ['is_other_places',false],
            ['is_visit',false],
            ['order_type','mini'],
            ['car_id',0],
            ['car_no',0]

        ]);
        $data['uid'] = $request->uid();
        if (!$data['contact_id']) throw new ValidateException('请添加用车人信息');
        $user = $request->user();
        return app('json')->success($this->services->createOrder($data,$user,1));
    }



    public function payOrder2(Request $request){
        $data = $request->getMore([
            ['order_id',''],
            ['pay_type','weixin']
        ]);
        $data['uid'] = $request->uid();
        $userInfo = $request->user();
        $userInfo['user_name'] = $userInfo['nickname'];
        $order = CarOrder::where('id',$data['order_id'])->find()->toArray();
        CarOrder::update(['id'=>$order['id'],'is_submit'=>1,'pay_num'=>$order['pay_num']+1]);
        $user = User::where('uid',$data['uid'])->find();
        if ($order['pay_time']>0){
            throw new ValidateException('订单已支付，不可重复支付');
        }
        /** @var OrderPayServices $payServices */
        $payServices = app()->make(OrderPayServices::class);
        switch ($data['pay_type']){
            case 'yue':
                if ($user['now_money']<$order['price']) throw new ValidateException('当前余额不足，请及时充值');
                $pay = $payServices->yueCarOrderPay($order, $data['uid'],$userInfo,1);
                if ($pay['status'] === true)
                    return app('json')->status('success', '余额支付成功', []);
                else {
                    if (is_array($pay))
                        throw new ValidateException($pay['msg']);
                    else
                        throw new ValidateException($pay);
                }
                break;
            case 'Offline':
                break;
            case 'weixin':
                if ($order['price']<=0){
                    throw new ValidateException('支付订单金额不能小于或等于0');
                }else{
                    $from = 'routine';
                    $jsConfig = $payServices->orderPay($order, $from,$userInfo,1);
                   if($jsConfig['success']==1){
                       return  app('json')->status('success', '请求支付成功', $jsConfig['result']);
                   }else{
                       throw new ValidateException($jsConfig['message']);
                   }
                }
                break;
        }
    }


    /**
     * 订单支付  微信官方支付
     * 2023年11月3日11:09:00 注释
     * @param Request $request
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function payOrder(Request $request){
        $data = $request->getMore([
            ['order_id',''],
            ['pay_type','weixin'],
            ['order_type','mini'],
        ]);
        $data['order_type'] = 'mini';
        $data['uid'] = $request->uid();
        $userInfo = $request->user();
        $userInfo['user_name'] = $userInfo['nickname'];
        $order = CarOrder::where('id',$data['order_id'])->find()->toArray();
        CarOrder::update(['id'=>$order['id'],'is_submit'=>1,'pay_num'=>$order['pay_num']+1]);
        $user = User::where('uid',$data['uid'])->find();
        if ($order['pay_time']>0){
            throw new ValidateException('订单已支付，不可重复支付');
        }
        /** @var OrderPayServices $payServices */
        $payServices = app()->make(OrderPayServices::class);
        switch ($data['pay_type']){
            case 'yue':
                if ($user['now_money']<$order['price']) throw new ValidateException('当前余额不足，请及时充值');
                $pay = $payServices->yueCarOrderPay($order, $data['uid'],$userInfo,1);
                if ($pay['status'] === true)
                    return app('json')->status('success', '余额支付成功', []);
                else {
                    if (is_array($pay))
                        throw new ValidateException($pay['msg']);
                    else
                        throw new ValidateException($pay);
                }
                break;
            case 'Offline':
                break;
            case 'weixin':
                if ($order['price']<=0){
                    throw new ValidateException('支付订单金额不能小于或等于0');
                }else{
                    $from = 'routine';
                    $jsConfig = $payServices->orderPay($order, $from,$userInfo,1,$data['order_type']);
                    return app('json')->status('wechat_pay', ['jsConfig' => $jsConfig, 'order_id' => $order['id']]);
                }
                break;
        }
    }

    /**
     * 押金支付
     * @param Request $request
     * @param CarOrderTakeServices $services
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function payDeposit(Request $request,CarOrderTakeServices $services){
        $data = $request->postMore([
            ['order_id',''],
            ['deposit_pay_type','weixin']
        ]);
        $take_id = CarOrder::where(['id'=>$data['order_id']])->value('take_id');
        if(!$take_id) return app('json')->fail('未查询到取车信息');
        $take_order = CarOrderTake::find($take_id);
        $take_order = $take_order ? $take_order->toArray() : [];
        if(!$take_order) return app('json')->fail('未查询到取车信息');
        if($take_order['deposit_is_pay']) return app('json')->fail('押金已支付');
        $userInfo = $request->user();
        /** @var OrderPayServices $payServices */
        $payServices = app()->make(OrderPayServices::class);
        switch ($data['deposit_pay_type']){
            case 'weixin':
                $from = 'routine';
                $jsConfig = $payServices->depositPay($take_order,$from,$userInfo,1);
//                if($jsConfig['success']==1){
//                    return  app('json')->status('success', '请求支付成功', $jsConfig['result']);
//                }else{
//                    throw new ValidateException($jsConfig['message']);
//                }
                return app('json')->status('wechat_pay',['jsConfig'=>$jsConfig, 'take_id'=>$take_order['id']]);
                break;
        }
    }
}
